package com.fjec.info.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.util.AliOSSUtil;
import com.fjec.common.util.DateUtil;
import com.fjec.common.view.InfoDetailVO;
import com.fjec.common.view.InfoInformationVO;
import com.fjec.common.view.RpcReturnPage;
import com.fjec.info.entity.InfoInformation;
import com.fjec.info.mapper.InfoInformationMapper;
import com.fjec.info.service.IInfoInformationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 025.资讯表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-12-12
 */
@Service
public class InfoInformationServiceImpl extends ServiceImpl<InfoInformationMapper, InfoInformation> implements IInfoInformationService {

    @Resource
    private InfoInformationMapper mapper;

    @Resource(name = "storeAliOSSUtil")
    private AliOSSUtil storeAliOSSUtil;

    @Override
    public JsonResult getInformationPage(Page page, Integer category) throws Exception {
        QueryWrapper<InfoInformation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DelFlag", 0)
                .eq("Display", 1)
                .eq("Category", category)
                .orderByDesc("GetTop")
                .orderByDesc("UpdateTime");
        Page<InfoInformation> entityPage = mapper.selectPage(page, queryWrapper);
        List<InfoInformationVO> resultList = new ArrayList<>();
        for (InfoInformation entity : entityPage.getRecords()) {
            InfoInformationVO view = new InfoInformationVO();
            BeanUtils.copyProperties(view, entity);
            view.setStrUpdateTime(DateUtil.format(entity.getUpdateTime(), "yyyy-MM-dd"));
            resultList.add(view);
        }
        return JsonResult.success()
                .total(entityPage.getTotal())
                .data(resultList)
                .build();
    }

    @Override
    public JsonResult getInfoDetail(Long id) throws Exception {
        InfoInformation entity = mapper.selectById(id);
        InfoDetailVO view = null;
        if (entity != null) {
            view = new InfoDetailVO();
            BeanUtils.copyProperties(view, entity);
            view.setSpace(MapUtils.getInteger(entity.getBizData(), "space"));
        }
        return JsonResult.success()
                .data(view)
                .build();
    }

    @Override
    public RpcReturnPage<InfoInformationVO> rpcGetInformationPage(Page page, String title, String startTime,
                                                                  String endTime, Integer getTop, Integer category) throws Exception {
        QueryWrapper<InfoInformation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DelFlag", 0)
                .orderByDesc("Display")
                .orderByDesc("UpdateTime");
        if (category != null) {
            queryWrapper.eq("Category", category);
        }
        if (!StringUtils.isEmpty(title)) {
            queryWrapper.like("title", "%" + title + "%");
        }
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
            LocalDateTime sTime = LocalDateTime.of(DateUtil.parseLd(startTime, "yyyy-MM-dd"), LocalTime.MIN);
            LocalDateTime eTime = LocalDateTime.of(DateUtil.parseLd(endTime, "yyyy-MM-dd"), LocalTime.MAX);
            queryWrapper.ge("UpdateTime", sTime)
                    .le("UpdateTime", eTime);
        }
        if (getTop != null) {
            queryWrapper.eq("GetTop", getTop);
        }
        Page<InfoInformation> entityPage = mapper.selectPage(page, queryWrapper);
        List<InfoInformationVO> resultList = new ArrayList<>();
        for (InfoInformation entity : entityPage.getRecords()) {
            InfoInformationVO view = new InfoInformationVO();
            BeanUtils.copyProperties(view, entity);
            if (category == 2) {
                view.setLinkUrl("/pages/indexPage/article/articleDetail?id=" + entity.getId());
            }
            resultList.add(view);
        }
        RpcReturnPage<InfoInformationVO> result = new RpcReturnPage<>();
        result.setDataList(resultList);
        result.setTotal(entityPage.getTotal());
        return result;
    }

    @Override
    public boolean rpcSaveOrUpdateInformation(Integer category, Long id, String title, String summary, String coverPic,
                                              String content, Integer display, Integer getTop, Integer space) {
        boolean result = false;
        InfoInformation entity;
        if (id != null && id != 0L) {
            // 更新
            entity = mapper.selectById(id);
        } else {
            // 新增
            entity = new InfoInformation();
            entity.setDelFlag(0);
            entity.setCreateTime(DateUtil.nowLdt());
        }
        if (entity != null) {
            entity.setCategory(category);
            entity.setTitle(title);
            entity.setSummary(summary);
            entity.setCoverPic(coverPic);
            entity.setContent(content);
            entity.setDisplay(display);
            entity.setGetTop(getTop);
            Map<String, Object> map = new HashMap<>();
            map.put("space", space);
            entity.setBizData(map);
            entity.setUpdateTime(DateUtil.nowLdt());
            result = this.saveOrUpdate(entity);
        }
        return result;
    }

    @Override
    public boolean rpcLogicDelInformation(Long id) {
        boolean result = false;
        InfoInformation entity = mapper.selectById(id);
        if (entity != null) {
            entity.setDelFlag(1);
            entity.setUpdateTime(DateUtil.nowLdt());
            result = this.updateById(entity);
        }
        return result;
    }

    @Override
    public InfoDetailVO rpcGetInfoDetail(Long id) throws Exception {
        InfoInformation entity = mapper.selectById(id);
        InfoDetailVO view = null;
        if (entity != null) {
            view = new InfoDetailVO();
            view.setSpace(MapUtils.getInteger(entity.getBizData(), "space"));
            BeanUtils.copyProperties(view, entity);
            if (view.getVideos() == null) {
                view.setVideos(new ArrayList<>());
            }
        }
        return view;
    }

    @Override
    public JsonResult uploadRichTextPic(MultipartFile file) throws Exception {
        JsonResult jsonResult = JsonResult.failure().build();
        Map<String, String> map = storeAliOSSUtil.uploadFile(file.getInputStream(), file.getContentType(), file.getOriginalFilename());
        if (map != null && map.containsKey("url")) {
            jsonResult = JsonResult.success()
                    .data(MapUtils.getString(map, "url"))
                    .build();
        }
        return jsonResult;
    }
}
